﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using DBTools.DBUpdate.Comm;

namespace DBTools.DBUpdate
{
    public partial class FormUpdate : Form
    {
        #region 变量
        bool _IsEditMode = false;

        public bool IsEditMode
        {
            get { return _IsEditMode; }
            set { _IsEditMode = value; }
        }

        string _AutoLoadUpFile = "";

        public string AutoLoadUpFile
        {
            get { return _AutoLoadUpFile; }
            set { _AutoLoadUpFile = value; }
        }
        bool _IsRun = false;//是否正在运行的状态
        #endregion

        public FormUpdate()
        {
            InitializeComponent();
        }


        private void ToolStripMenuItem_Exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void FormUpdate_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("是否关闭退出当前程序？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
            {
                e.Cancel = true;
            }
        }

        private void toolStripButton_Exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void ToolStripMenuItem_About_Click(object sender, EventArgs e)
        {
            AboutBoxUser _ShowForm = new AboutBoxUser();
            _ShowForm.ShowDialog();
        }

        private void ToolStripMenuItem_Set_Click(object sender, EventArgs e)
        {
            SettingForm _ShowForm = new SettingForm();
            _ShowForm.ShowDialog();
            toolStripStatusLabel_ServerInfo.Text = Set.ServerIp;
        }

        private void toolStripButton_Set_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem_Set_Click(null, null);
        }

        private void toolStripButton_Info_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem_About_Click(null, null);
        }

        private void ToolStripMenuItem_Run_Click(object sender, EventArgs e)
        {
            if (Set.DbServerConnectionString == "")
            {
                MessageComm.ShowError("数据库连接配置为空!");
                return;
            }
            InitRuncontrol();
            string _StartVersion = "2000-01-01";
            string _LastVersion = "";

            #region 检查现有库中是否有表
            DataSet _Tempds = Mssql.Query(TableSqlHelper.GetDBVersionSqlString(Set.DataBaseName));
            if (_Tempds == null || _Tempds.Tables.Count == 0 || _Tempds.Tables[0].Rows.Count == 0)
            {
                MessageComm.ShowWarning("没有取到本地数据库，系统将自动生成相应底库!");

                if (Mssql.ExecuteNonQuery(TableSqlHelper.CreteaInitDBVersionSqlString(Set.DataBaseName, Set.SystempName)) < 0)
                {
                    MessageComm.ShowWarning("系统自动生成底库失败!");
                    return;
                }
            }
            else
            {
                _StartVersion = _Tempds.Tables[0].Rows[0][0].ToString().Trim();
            }
            #endregion

            _IsRun = true;
            _LastVersion = RunFromPath(Set.TempFolder, _StartVersion);
            if (_IsRun)
            {
                #region 更新最后版本
                textBox_Logs.Text = textBox_Logs.Text + "\r\n执行结束版本" + _LastVersion;
                Mssql.ExecuteNonQuery(TableSqlHelper.UpdateDBVersionSqlString(Set.DataBaseName, _LastVersion));
                MessageComm.ShowInfo(string.Format("升级成功\r\n版本：{0}", _LastVersion));
                #endregion
            }
            else
            {
                textBox_Logs.Text = textBox_Logs.Text + "\r\n执行结束版本" + _StartVersion;
                MessageComm.ShowError(string.Format("升级失败\r\n版本：{0}", _StartVersion));
            }
            _IsRun = false;
        }


        #region run
        private void InitRuncontrol()
        {
            label_RunFileName.Text = "";
            progressBar_SumRate.Minimum = 0;
            progressBar_SumRate.Maximum = 100;
            progressBar_SumRate.Value = 0;
            progressBar_RunRate.Minimum = 0;
            progressBar_RunRate.Maximum = 100;
            progressBar_RunRate.Value = 0;
        }
        private void UpdateCpuProgress(ProgressBar progressBar_Temp)
        {
            string strText = progressBar_Temp.Value.ToString() + "%";
            Font font = new Font("微软雅黑", (float)10, FontStyle.Regular);
            PointF pointF = new PointF(progressBar_Temp.Width / 2 - 10, progressBar_Temp.Height / 2 - 10);
            progressBar_Temp.CreateGraphics().DrawString(strText, font, Brushes.Black, pointF);
        }
        private string RunFromPath(string _SourcePath, string _StartVersion)
        {
            textBox_Logs.Text = textBox_Logs.Text + "\r\n初始版本" + _StartVersion;
            string _LastVersion = RunFiles(_SourcePath, _StartVersion, true);
            return _LastVersion;
        }
        private string RunFiles(string _SourcePath, string _StartVersion, bool _IsTop = false)
        {
            if (!_IsRun)
            {
                _IsRun = false;
                return "因失败未执行!";
            }
            string _LastVersion = "";
            if (!_IsTop)
            {
                _LastVersion = _SourcePath.GetLastDirectoryItemValue();
                if (string.Compare(_LastVersion, _StartVersion) <= 0)
                {
                    textBox_Logs.Text = textBox_Logs.Text + "\r\n跳过" + _LastVersion;
                    return _LastVersion;//这个版本已经执行完成
                }
                else
                {
                    textBox_Logs.Text = textBox_Logs.Text + "\r\n执行" + _LastVersion;
                }
            }

            string[] _Dics = Directory.GetDirectories(_SourcePath);
            if (_IsTop)
            {
                progressBar_SumRate.Minimum = 0;
                progressBar_SumRate.Maximum = _Dics.Length;
            }
            int _Seek = 0;
            foreach (string dic in _Dics)
            {
                if (_IsTop)
                {
                    progressBar_SumRate.Value = ++_Seek;
                    UpdateCpuProgress(progressBar_SumRate);
                }
                _LastVersion = dic.GetLastDirectoryItemValue();
                RunFiles(dic, _StartVersion);
            }
            string[] _Files = Directory.GetFiles(_SourcePath);
            progressBar_RunRate.Minimum = 0;
            progressBar_RunRate.Maximum = _Files.Length;
            progressBar_RunRate.Value = 0;
            int _SeekFile = 0;
            foreach (string _FileItem in _Files)
            {
                Application.DoEvents();
                progressBar_RunRate.Value = ++_SeekFile;
                UpdateCpuProgress(progressBar_RunRate);
                if (new FileInfo(_FileItem).Extension.ToUpper() != ".SQL")
                {
                    continue;
                }
                label_RunFileName.Text = _FileItem.Replace(Set.TempFolder, "\\");
                textBox_Logs.Text += ("\r\n" + _FileItem.Replace(Set.TempFolder, "\\"));
                string _RunSql = Export.ReadText(_FileItem).ClearItem("go", "-&go&-").ToInString("\r\n");

            IL500:
                try
                {
                    Mssql.ExecuteNonQuery(System.Text.RegularExpressions.Regex.Split(_RunSql, "-&go&-").ToList());
                }
                catch (Exception ex)
                {
                    textBox_Error.Text += string.Format("---------------------------------{0}---------------------------\r\n{1}\r\n{2}\r\n",
                        DateTime.Now.ToString("yyy-MM-dd HH:mm:ss"),
                        _FileItem.Replace(Set.TempFolder, "\\"), ex.Message);
                    DialogResult _Result = MessageBox.Show("执行错误，请选择操作？", "提示", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Question);
                    if (_Result == DialogResult.Abort)
                    {
                        //中止
                        _IsRun = false;
                        break;
                    }
                    else if (_Result == DialogResult.Retry)
                    {
                        //重试
                        goto IL500;
                    }
                    else
                    {
                        //忽略，不管
                    }
                }
            }
            return _LastVersion;
        }


        #endregion

        private void ToolStripMenuItem_SaveUpdateFile_Click(object sender, EventArgs e)
        {
            SaveFileDialog _ShowSaveUpdateFile = new SaveFileDialog();
            _ShowSaveUpdateFile.Filter = "update升级文件|*.u";
            if (_ShowSaveUpdateFile.ShowDialog() == DialogResult.OK)
            {
                string _FileName = _ShowSaveUpdateFile.FileName;
                if (new FileInfo(_FileName).Extension.ToUpper() != ".U")
                {
                    _FileName = _FileName + ".u";
                }
                (new FastZip()).CreateZip(_FileName, Set.SelectFolder, true, "");
                MessageComm.ShowInfo(string.Format("生成升级包成功。\r\n{0}", _FileName));
            }
        }

        private void ToolStripMenuItem_Open_Click(object sender, EventArgs e)
        {
            OpenFileDialog _ShowOpenFileForm = new OpenFileDialog();
            _ShowOpenFileForm.Filter = "update升级文件|*.u";
            if (_ShowOpenFileForm.ShowDialog() == DialogResult.OK)
            {
                OpenUpdateFile(_ShowOpenFileForm.FileName);
            }
        }
        private void OpenUpdateFile(string _FileName)
        {
            if (new FileInfo(_FileName).Extension.ToUpper() != ".U")
            {
                MessageComm.ShowError("请选择正确的升级包文件！");
                return;
            }

            #region 解压文件
            string _RealPath = Set.TempFolder + Guid.NewGuid().ToString() + "\\";
            System.IO.Directory.CreateDirectory(_RealPath);
            (new FastZip()).ExtractZip(_FileName, _RealPath, "");
            #endregion


            #region 加载ini
            string _DbIniFile = _RealPath + "DBinfo.ini";
            if (File.Exists(_DbIniFile))
            {
                Ini.IniFileName = _DbIniFile;
                Set.DataBaseName = Ini.GetIniSetStr("Info", "DB", "");
                Set.SystempName = Ini.GetIniSetStr("Info", "Name", "");
            }
            else
            {
                MessageComm.ShowError("包内没有找到配置文件DBInfo.ini,请重新生成升级包!");
                return;
            }
            #endregion
            Set.TempFolder = _RealPath;
            Set.SelectFolder = _RealPath;

            toolStripStatusLabel_FileInfo.Text = string.Format("[{0}][{1}]", Set.DataBaseName, Set.SystempName);

            #region 加载信息
            LoadNodesFromPath(Set.TempFolder);
            #endregion
        }

        private void toolStripButton_Open_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem_Open_Click(null, null);
        }

        private void toolStripButton_Run_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem_Run_Click(null, null);
        }

        private void ToolStripMenuItem_OpenDirectory_Click(object sender, EventArgs e)
        {
            #region  打开目录
            FolderBrowserDialog _ShowForm = new FolderBrowserDialog();
            if (Set.SelectFolder != "")
            {
                _ShowForm.SelectedPath = Set.SelectFolder;
            }
            if (_ShowForm.ShowDialog() == DialogResult.OK)
            {
                textBox_Sql.Text = "";
                textBox_Error.Text = "";

                if (!File.Exists(_ShowForm.SelectedPath + "\\DBInfo.ini"))
                {
                    DBInfoForm _ShowDBInfoForm = new DBInfoForm();
                    _ShowDBInfoForm.TargetPath = _ShowForm.SelectedPath;
                    if (_ShowDBInfoForm.ShowDialog() != DialogResult.OK)
                    {
                        return;
                    }
                }
                Set.SelectFolder = _ShowForm.SelectedPath;
                LoadNodesFromPath(Set.SelectFolder);
            }
            #endregion
        }

        private void LoadNodesFromPath(string _SourcePath)
        {
            treeView_FilesTree.Nodes.Clear();
            LoadNode(_SourcePath, null, true);
            treeView_FilesTree.ExpandAll();
        }
        private void LoadNode(string _SourcePath, TreeNode _CurrentNode, bool _IsTop = false)
        {
            //获取指定目录中的子目录名称并加载结点
            string[] _Dics = Directory.GetDirectories(_SourcePath);
            foreach (string dic in _Dics)
            {
                TreeNode subNode = new TreeNode(new DirectoryInfo(dic).Name); //实例化
                subNode.Name = new DirectoryInfo(dic).FullName;               //完整目录
                subNode.Tag = subNode.Name;
                subNode.ImageIndex = IconIndexes.NormalFolder;       //设置获取节点显示图片
                subNode.SelectedImageIndex = IconIndexes.OpenFolder; //设置选择节点显示图片
                if (_IsTop)
                {
                    treeView_FilesTree.Nodes.Add(subNode);
                }
                else
                {
                    _CurrentNode.Nodes.Add(subNode);
                }
                LoadNode(dic, subNode);

            }
            string[] _Files = Directory.GetFiles(_SourcePath);
            foreach (string _FileItem in _Files)
            {
                TreeNode subNode = new TreeNode(new FileInfo(_FileItem).Name); //实例化
                subNode.Name = new FileInfo(_FileItem).FullName;               //完整目录
                subNode.Tag = subNode.Name;
                if (new FileInfo(_FileItem).Extension.ToUpper() == ".SQL")
                {
                    subNode.ImageIndex = IconIndexes.NormalFile;       //设置获取节点显示图片
                    subNode.SelectedImageIndex = IconIndexes.OpenFile; //设置选择节点显示图片
                }
                else
                {
                    subNode.ImageIndex = IconIndexes.OtherFile;       //设置获取节点显示图片
                    subNode.SelectedImageIndex = IconIndexes.OtherFile; //设置选择节点显示图片

                }
                if (_IsTop)
                {
                    treeView_FilesTree.Nodes.Add(subNode);
                }
                else
                {
                    _CurrentNode.Nodes.Add(subNode);
                }
            }

        }





        private void toolStripButton_OpenDirectory_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem_OpenDirectory_Click(null, null);
        }

        private void toolStripButton_SaveFile_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem_SaveUpdateFile_Click(null, null);
        }

        private void toolStripButton_OpenUpdateFile_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem_OpenEditFile_Click(null, null);
        }

        private void ToolStripMenuItem_OpenEditFile_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem_Open_Click(null, null);//此处应该单独开一个业务出来
        }

        private void ToolStripMenuItem_ViewFileInfo_Click(object sender, EventArgs e)
        {
            toolStripButton_ViewFileInfo_Click(null, null);
        }

        private void toolStripButton_ViewFileInfo_Click(object sender, EventArgs e)
        {
            MessageBox.Show("查看升级包信息");
        }

        private void treeView_FilesTree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode clickedNode = e.Node;
            if (File.Exists(clickedNode.Tag.ToString()))
            {
                #region  显示选择文件内容
                textBox_Sql.Text = Export.ReadText(clickedNode.Tag.ToString()).ToInString("\r\n");
                textBox_Error.Text = "";
                #endregion
            }
        }

        private void FormUpdate_Load(object sender, EventArgs e)
        {
            if (_IsEditMode)
            { }
            else
            {
                ToolStripMenuItem_Edit.Visible = false;
                toolStripButton_OpenDirectory.Visible = false;
                toolStripButton_OpenUpdateFile.Visible = false;
                toolStripButton_SaveFile.Visible = false;
                toolStripButton_ViewFileInfo.Visible = false;
                toolStripSeparator2.Visible = false;
            }
            if (_AutoLoadUpFile != "")
            {
                OpenUpdateFile(_AutoLoadUpFile);
            }
            #region  其它信息
            this.Text = string.Format("{0}[{1}]", AssemblyHelper.AssemblyTitle, AssemblyHelper.AssemblyVersion);
            #endregion
        }
    }
    public class IconIndexes
    {
        public const int NormalFolder = 0;      //文件夹关闭
        public const int OpenFolder = 1;      //文件夹打开      
        public const int NormalFile = 2;     //普通脚本文件
        public const int OpenFile = 3;     //普通脚本文件
        public const int OtherFile = 4;     //其它文件
    }
}
